<template>
    <div class="pageWrapper">
        <SearchBar class="form" @onSearch="handleSearch" @childFn="resetForm">
            <SearchBarItem label="商户号：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.subMchId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="商品名称：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.productName"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="付款账户名：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.payAcct"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="收款账户名：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.colAcct"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="费用类型：" :labelLg="8">
                <Select
                    v-model="dataModule.costType"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in costType"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="交易日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="payDatePicker"
                    split-panels
                    transfer
                    placeholder="起始时间"
                    @on-change="payTime"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="是否有差异：" :labelLg="8">
                <Select
                    v-model="dataModule.isException"
                    placeholder="请选择"
                    :clearable="isClear"
                >
                    <Option
                        :value="item.key"
                        v-for="(item, key) in diffList"
                        :key="key"
                        >{{ item.value }}</Option
                    >
                </Select>
            </SearchBarItem>
            <SearchBarItem label="主订单：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.orderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="子订单：" :labelLg="8">
                <Input
                    type="text"
                    v-model="dataModule.subOrderId"
                    placeholder="请输入"
                    clearable
                />
            </SearchBarItem>
            <SearchBarItem label="对账日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="billDatePicker"
                    split-panels
                    transfer
                    placeholder="起始时间"
                    @on-change="billTime"
                ></DatePicker>
            </SearchBarItem>
            <SearchBarItem label="核销日期：" :labelLg="8">
                <DatePicker
                    type="daterange"
                    ref="verifiedDatePicker"
                    split-panels
                    transfer
                    placeholder="起始时间"
                    @on-change="verifiedTime"
                ></DatePicker>
            </SearchBarItem>
        </SearchBar>
        <RemoteTable
            ref="remoteTable"
            :namespace="namespace"
            :columns="columns"
            :showPageInfo="false"
            :showCount="true"
            :isFixedHeader="true"
            :selected="exportData"
            @onSelectionChange="getListChecked"
        >
          <template #extra>
            <Authc permissions="trade:settlement:cmb">
              <Button type="primary" @click="exportExcel">导出</Button>
            </Authc>
          </template>

        </RemoteTable>
        <br />
        <Row>
            <Col span="12" offset="11">
                <Button type="primary" :disabled="isDisabledloadBtn" @click="loadMore">加载更多</Button>
            </Col>
        </Row>
    </div>
</template>
<script>
import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Tabs,
    TabPane
} from "view-design";
import RemoteTable from "@/components/RemoteTable";
import SearchBar from "@/components/SearchBar";
import RemoteSelect from "@/components/RemoteSelect";
import { namespace } from "../../Module/clearingDeteleAccountModule";
import Authc from "@/components/Authc";
import Tables from "@/components/tables";
import Action from "./Action";
import config from "@/utils/config";
import util from "@/utils/util";
import appService from "@/utils/appService";

export default {
    name: "clearingDetele",
    components: {
        RemoteTable,
        SearchBar,
        SearchBarItem: SearchBar.SearchBarItem,
        RemoteSelect,
        Authc,
        Action,
        Tables,
        Button,
        Input,
        Modal,
        Message,
        Col,
        Row,
        Form,
        FormItem,
        DatePicker,
        Select,
        Option,
        Card,
        Tabs,
        TabPane
    },
    props: {
        clearingDate: Array,
        subMchId: String,
        costTypeStatus: String,
        isClearQuery: Boolean
    },
    data() {
        return {
            requireUrl: "",
            namespace: namespace,
            isClear: true,
            loading: true,
            modal1: false,
            diffList: [
                {
                    key: "1",
                    value: "是"
                },
                {
                    key: "0",
                    value: "否"
                }
            ],/** 是否有差异 **/
            costType: [], /** 费用类型 **/
            dataModule: {}, //查询条件
            isDisabledloadBtn: false, /** 控制加载更多按钮 **/
            currentPage: 1, /** 用来控制加载更新 **/
            exportData: [], /** 导出数据 **/
            columns: [
                {
                    title: "平台清分订单明细",
                    align: "center",
                    children: [
                        {
                            type: "selection",
                            align: "center",
                            minWidth: 55
                        },
                        {
                            title: "序号",
                            type: "index",
                            align: "center",
                            minWidth: 70
                        },
                        {
                            title: "清分日期",
                            key: 'shouldClearDate',
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "费用类型",
                            key: "costTypeName",
                            align: "center",
                            minWidth: 100
                        },
                        {
                            title: "主订单",
                            key: "orderId",
                            align: "center",
                            minWidth: 200,
                            render: (h, params) => {
                                let item = params.row.systemDataFlag === '0' ? params.row.orderId : '';
                                return h('span', item);
                            }
                        },
                        {
                            title: "子订单",
                            key: "subOrderId",
                            align: "center",
                            minWidth: 180,
                            render: (h, params) => {
                                let item = params.row.systemDataFlag === '0' ? params.row.subOrderId : '';
                                return h('span', item);
                            }
                        },
                        {
                            title: "商户号",
                            key: "subMchId",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "商品名称",
                            key: "productName",
                            align: "center",
                            minWidth: 180,
                            render: (h, params) => {
                                let item = params.row.systemDataFlag === '0' ? params.row.productName : '';
                                return h('span', item);
                            }
                        },
                        {
                            title: "付款账户名",
                            key: "payAcctName",
                            align: "center",
                            minWidth: 180,
                            render: (h, params) => {
                                let item = params.row.systemDataFlag === '0' ? params.row.payAcctName : '';
                                return h('span', item);
                            }
                        },
                        {
                            title: "收款账户名",
                            key: "colAcctName",
                            align: "center",
                            minWidth: 190,
                            render: (h, params) => {
                                let item = params.row.systemDataFlag === '0' ? params.row.colAcctName : '';
                                return h('span', item);
                            }
                        },
                        {
                            title: "清分金额(元)",
                            key: "clearAmount",
                            align: "center",
                            minWidth: 140,
                            render: function(h, params){
                                let item = params.row.systemDataFlag === '0' ? util.toMoney(params.row.clearAmount / 100) : '';
                                return h('span', item);
                            }
                        }
                    ]
                },
                {
                    title: "银行清分订单明细",
                    key: "gender",
                    align: "center",
                    children: [
                        {
                            title: "招行订单号",
                            key: "bankOrderId",
                            align: "center",
                            minWidth: 220
                        },
                        {
                            title: "清分金额(元)",
                            key: 'bankClearAmount',
                            align: "center",
                            minWidth: 140,
                            render: function(h, data){
                                let item = data.row.bankClearAmount / 100;
                                return h('span', util.toMoney(item));
                            }
                        },
                        {
                            title: "订单日期",
                            key: 'payTime',
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "核销日期",
                            key: 'verifiedTime',
                            align: "center",
                            minWidth: 180
                        }
                    ]
                },
                {
                    title: "对账处理",
                    key: "gender",
                    align: "center",
                    children: [
                        {
                            title: "对账日期",
                            key: "completeDate",
                            align: "center",
                            minWidth: 180
                        },
                        {
                            title: "差异",
                            key: 'errorAmount',
                            align: "center",
                            minWidth: 100,
                            render: (h, params) => {
                                return h('span', params.row.errorAmount / 100)
                            }
                        },
                        {
                            title: "差异原因",
                            key: 'errorRemark',
                            align: "center",
                            minWidth: 210
                        },
                        {
                            title: "对账次数",
                            key: 'billCount',
                            align: "center",
                            minWidth: 110
                        },
                        {
                            title: "操作",
                            key: "action",
                            align: "center",
                            permissions: ["trade:settlement:cmb"],
                            minWidth: 200,
                            render: function(h, data) {
                                return h(Action, {
                                    props: {
                                        row: data.row,
                                        isShowBtn: data.row.status === '0' ? false : true
                                    }
                                });
                            }
                        }
                    ]
                }
            ],
            dataItem: false
        };
    },
    created() {
       /**
         * 如果 url 没有带参数，就重置请求参数
         * 有就添加到 vuex
         * this.clearingDate 传过来的时间参数
        * **/
       let clearDate = util.getUrlParam('clearDate') || this.clearingDate;
    //    console.log(this.clearDate, this.clearDate, '1111111')
    //    console.log(clearDate, '----汇总跳转明细', this.costTypeStatus, this.subMchId)
        if (clearDate || this.costTypeStatus) {
            this.dataItem = true;
            this.$set(this.dataModule, 'costType', this.costTypeStatus)
            this.$set(this.dataModule, 'subMchId', this.subMchId)
            this.$store.commit(`${namespace}/setQuery`, {
                startDate: clearDate,
                endDate: clearDate,
                costType: this.costTypeStatus,
                subMchId: this.subMchId

            });
        }
        /** 这个判断是控制，是否从详情页面返回的，如果是从详情页面返回，然后有没有带有url的话，就清空vuex里面的请求参数
         * 否则就写入参数
         *  **/
        console.log(!clearDate, this.isClearQuery, '参数')
        if(!clearDate && this.isClearQuery) {
            // this.$store.commit(`${namespace}/reviseQuery`);
        } else if (util.getUrlParam('typeStatus')) {
            this.setDataModule();
        }
        this.getKey();
    },
    mounted() {
        setTimeout(() => {
            this.loading = false;
        }, 1000);
    },
    activated() {
        console.log('this.dataModule', this.dataModule)
        this.dataModule = JSON.parse(localStorage.getItem('data')) || {};
    },
    deactivated () {
        if (window.location.pathname.indexOf('clearingDeteleForm') > -1 ) {

        } else {
            this.$store.commit(`${namespace}/reviseQuery`);
            localStorage.removeItem('data');
            this.dataModule = {}
        }
    },
    watch: {
        /** 监听父组件是否改变了，商户 id
         *  这里是用来监听成功明细的点击操作
         *  **/
        subMchId(val){
            this.$set(this.dataModule, 'subMchId', val);
            console.log(val, 'newValue')
            this.handleSearch();
        },
        'isDisabledloadBtn' (val) {
            if (val) {
                let dataList = this.$store.state[namespace].pageInfo.list;
                for (let i = 0; i < dataList.length; i++) {
                    dataList[i]._checked = false;
                    for (let j = 0; j < this.exportData.length; j++) {
                        if (this.exportData[j].id == dataList[i].id) {
                            dataList[i]._checked = true;
                        }
                    }
                }
            }
        }
    },
    methods: {
        /** 导出 **/
        exportExcel() {
            if( this.exportData.length == 0 ) {
                this.$Message.error({
                    content: '请选择导出的数据'
                });
                return;
            } else {
                this.exportData.forEach(e => {
                    // if (e.clearAmount || e.bankClearAmount) {

                        e.costTypeName = e.costTypeName || '';
                        e.orderId = e.orderId || '';
                        e.subOrderId = e.subOrderId;
                        e.subMchId = e.subMchId || '';
                        // merchantCode:.merchantCode ? `\t$.merchantCode}` : '',
                        e.productName = e.productName || '';
                        e.payAcctName = e.payAcctName || '';
                        e.colAcctName = e.colAcctName || '';
                        e.clearAmount = (e.clearAmount / 100) || `\t0`;
                        e.bankOrderId = e.bankOrderId || '';
                        e.bankClearAmount = e.bankClearAmount || `\t0`;
                        e.payTime = e.payTime || '';
                        e.verifiedTime = e.verifiedTime || '';
                        e.completeDate = e.completeDate || '';
                        e.errorAmount = e.errorAmount || `\t0`;
                        e.errorRemark = e.errorRemark || '';
                        e.billCount = e.billCount || `\t0`;
                    // }
                })
            }

            /** 多表头处理 **/
            let exportColumn = this.handleMultiTableHeader(this.columns, false);

            /** 复制一份表头 **/
            let columnOne = {};
            exportColumn.forEach(item => {
                columnOne[item.key] = item.title;
            });

            /** 自定义导出表格第一行的表头，逗号表示隔开几个单元格 **/
            let tableTitle = {
                shouldClearDate: `${this.columns[0].title},,,,,,,,,${this.columns[1].title},,,,${this.columns[2].title}`,
                costTypeName: '',
                orderId: '',
                subOrderId: '',
                subMchId: '',
                // merchantCode: '',
                productName: '',
                payAcctName: '',
                colAcctName: '',
                clearAmount: '',
                bankOrderId: '',
                bankClearAmount: '',
                payTime: '',
                verifiedTime: '',
                completeDate: '',
                errorAmount: '',
                errorRemark: '',
                billCount: '',
            }
            /** 复制一份导出数据 **/
            let copyTableData = JSON.parse(JSON.stringify(this.exportData));

            /** 把自定义的表头和复制出来的表头，添加到导出数据前面 **/
           copyTableData.unshift(tableTitle, columnOne);
           console.log(copyTableData)

            let tables = this.$refs.remoteTable.getTables();
            tables.exportCsv({
                filename: '清分明细对账',
                columns: exportColumn,
                data: copyTableData.map(item => {
                    return {
                        shouldClearDate: `\t${item.shouldClearDate}`,
                        costTypeName: `\t${ item.costTypeName }`,
                        orderId: `\t${item.orderId}`,
                        subOrderId: `\t${item.subOrderId}`,
                        subMchId: `\t${item.subMchId}`,
                        // merchantCode: item.merchantCode ? `\t${item.merchantCode}` : '',
                        productName: `\t${ item.productName }`,
                        payAcctName: `\t${ item.payAcctName }`,
                        colAcctName: `\t${ item.colAcctName }`,
                        clearAmount: `\t${item.clearAmount}`,
                        bankOrderId: `\t${item.bankOrderId}`,
                        bankClearAmount: `\t${item.bankClearAmount}`,
                        payTime: `\t${item.payTime}`,
                        verifiedTime: `\t${item.verifiedTime}`,
                        completeDate: `\t${item.completeDate}`,
                        errorAmount: `\t${item.errorAmount}`,
                        errorRemark: `\t${ item.errorRemark }`,
                        billCount: `\t${item.billCount}`,
                    }
                }),
                noHeader: true
            });
        },
        /** 获取字典 **/
        async getKey(){
            try {
                let res = await this.$store.dispatch(`${namespace}/getMerchantSearchKey`);
                let data = res.data.data;
                this.costType = data.dataType;
                // this.selectTransactionType = data.transactionType;
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 搜索 **/
        handleSearch() {
            this.currentPage = 1;
            let obj = {
                currentPage: 1,
                pageSize: 50,
            };
            if ( this.clearingDate.length != 0 ) {
                obj.startDate = this.clearingDate[0];
                obj.endDate = this.clearingDate[1];
            } else {
                obj.startDate = util.fun_date(-7);
                obj.endDate = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate();
            }
            this.$store.dispatch(`${namespace}/query`, {...this.dataModule, ...obj});
            // localStorage.setItem('data', JSON.stringify(this.dataModule));
        },
        /** 加载更多 **/
        async loadMore() {
            try {
                let clearDate = this.clearingDate;
                let dateItem
                if (this.$route.query.clearDate || this.costTypeStatus || clearDate) {
                    dateItem = {
                        startDate: clearDate[0] || this.$route.query.clearDate,
                        endDate: clearDate[1] || this.$route.query.clearDate,
                        costType: this.costTypeStatus || this.dataModule.costType,
                        subMchId: this.subMchId || this.dataModule.subMchId
                    }
                }
                console.log(clearDate, this.dataModule, this.costTypeStatus, this.subMchId,  '时间')
                // if (this.dataItem) {
                //     dateItem = {
                //         startDate: clearDate[0] || this.$route.query.clearDate,
                //         endDate: clearDate[1] || this.$route.query.clearDate,
                //         costType: '',
                //         subMchId: ''
                //     }
                // }
                this.isDisabledloadBtn = true; /** 每次请求都禁止按钮点击 **/
                let obj = {
                    currentPage: ++this.currentPage,
                    pageSize: 50,
                };
                /** 因为不是翻页，所以重新写了一个列表的请求 **/
                let res = await this.$store.dispatch(`${namespace}/getMoreList`, { ...dateItem, ...this.dataModule, ...obj });
                let listData = res.data.data.list;
                if (listData.length != 0) {
                    /** 拿到数据，就拼接到 vuex 里面 **/
                    this.$store.commit(`${namespace}/pushDataToList`, listData);
                    this.isDisabledloadBtn = false;
                } else {
                    --this.currentPage;
                    this.$Message.info({
                        content: '没有更多数据了！'
                    });
                    this.isDisabledloadBtn = true;
                }
            } catch (error) {
                this.$Message.error({
                    content: error
                });
            }
        },
        /** 清空事件 **/
        resetForm() {
            this.$set(this.dataModule, 'subMchId', '');
            this.$set(this.dataModule, 'productName', '');
            this.$set(this.dataModule, 'payAcct', '');
            this.$set(this.dataModule, 'colAcct', '');
            this.$set(this.dataModule, 'costType', '');
            this.$set(this.dataModule, 'isException', '');
            this.$set(this.dataModule, 'orderId', '');
            this.$set(this.dataModule, 'subOrderId', '');
            // 清空时间选择
            this.$refs["payDatePicker"].handleClear();
            this.$refs["billDatePicker"].handleClear();
            this.$refs["verifiedDatePicker"].handleClear();
        },
        /** 交易日期 **/
        payTime(date, type) {
            this.dataModule.payStartTime = date ? date[0] : "";
            this.dataModule.payEndTime = date ? date[1] : "";
        },
        /** 对账日期 **/
        billTime(date, type) {
            this.dataModule.billStartDate = date ? date[0] : "";
            this.dataModule.billEndDate = date ? date[1] : "";
        },
        /** 核销日期 **/
        verifiedTime(date, type) {
            this.dataModule.verified_start_time = date ? date[0] : "";
            this.dataModule.verified_end_time = date ? date[1] : "";
        },
        /** 获取选中的数据 **/
        getListChecked(data, index){
            this.exportData = data;
        },
        /** cy 处理多表头导出问题 **/
        handleMultiTableHeader (columns) {
            return columns.map(res => {
                if (res.hasOwnProperty('children')) {
                    /** 通过 key 过滤掉 复选框和序号还有操作栏 **/
                    return res.children.filter(item => {
                        return item.key;
                    })
                } else {
                    return res;
                }
            }).flat();
        },
        /** 返回的时候设置下搜索参数 **/
        setDataModule(){
            for(const key in this.$store.state[`${namespace}`].query) {
                if ( key != 'currentPage' && key != 'pageSize') {
                    this.dataModule[key] = this.$store.state[`${namespace}`].query[key];
                }
            }
        }
    },
};
</script>
<style scoped>
.bottom_count {
    text-align: right;
}
</style>
